package com.ydd.common.handler;



import com.ydd.common.exception.BusinessException;
import com.ydd.common.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;


import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * @Description: 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 数据库操作异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = DataAccessException.class)
    @ResponseBody
    public ResponseResult<String> dataAccessException(DataAccessException e) {
        log.error(e.getMessage(), e);
        Throwable throwable = getThrowable(e);
        return ResponseResult.error("数据库异常：" + throwable.getMessage());
    }




    /**
     * 自定义业务异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseResult<String> businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 全局异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult<String> handleException(Exception e) {
        log.error(e.getMessage(), e);
        Throwable throwable = getThrowable(e);
        return ResponseResult.error("服务器异常：" + throwable.getMessage());
    }


    /**
     * @description 获取最里层异常
     */
    private Throwable getThrowable(Throwable throwable) {
        Throwable result = throwable;
        while (result.getCause() != null) {
            result = result.getCause();
        }

        return result;
    }
}
